Motivation

Many automation scripts require credentials in order to function properly. Manual input is not very convinient and prevents automation. Thus encrypting credentials in a config file and decrypting credentials on demand by script is a nice feature for make life easier while keeping risks lower. sops is a tool to encrypt/decrypt a whole file or encryt/decryt partial fields in supprted formats like yaml, json, ini, env and binary with AWS KMS, GCP KMS, Azure Key Vault and PGP.

Disclaim

sops uses gnupg to encrypt/decrypt credentials. sec key is stored under ~/.gnupg without password protection to make automation possbile. It is critical to keep your account safe. Also it is only recommended to store less critical credentials and generate dedicated pub/sec keys for this purpose.

Preparation

create a test.yaml first.

user: test
password: pwd

Install gnupg, sops.

Generate a pgp key pair with on passphrase and no expiration date.

gpg --batch --generate-key <<EOF
%no-protection
Key-Type: default
Subkey-Type: default
Name-Real: app
Name-Email: app@domain.com
Expire-Date: 0
EOF

Find public fingerprint:

gpg --list-keys "app@domain.com" | grep pub -A 1 | gpre -v pub

Backup keys:

gpg --export -a "app@domain.com" > pub.key
gpg --export-secret-key -a "app@domain.com" > sec.key

Import keys on other machines: gpg --import pub.key gpg --allow-secret-key-import -- import sec.key

Create .sops.yaml under workding directory.

creation_rules:
    - pgp: >-
        pubkey fingerprint here

Play with sops

Ensure there is .sops.yaml under CWD.

Encrypt whole file

sops -e --in-place test.yaml

Encrypt certain fields only

sops -e --in-place --encrypted-regex 'user|password' test.yaml

Decrypt whole file

sops -d test.yaml

Extract a sub-part of an encrypted file.

sops -d --extract '["user"]' test.yaml

Feed sops's output to cmd

cmd expects a fd

sops -d test.yaml | sudo cmd ... --opt /dev/stdin

cmd expects values

sudo cmd ... --opt $(sops -d --extract '["user"]' test.yaml)

Published

Category

Linux

Tags

Contact